package com.rakuten.api.mule.transformers;

import java.util.ArrayList;
import java.util.List;

import org.mule.api.MuleMessage;
import org.mule.api.transformer.TransformerException;
import org.mule.api.transport.PropertyScope;
import org.mule.transformer.AbstractMessageTransformer;

import com.rakuten.api.mule.CommonFlowConstants;
import com.rakuten.api.mule.model.Product;
import com.rakuten.api.mule.model.Variant;
import com.rakuten.api.mule.response.UpdateProductResponseRMS;

public class BuildUpdateProductResponse extends AbstractMessageTransformer {

	public BuildUpdateProductResponse() {
		super();
	}

	@Override
	public Object transformMessage(MuleMessage message, String outputEncoding)
			throws TransformerException {
		try {
			UpdateProductResponseRMS updateProductResponseRMS = message
					.getPayload(UpdateProductResponseRMS.class);
			if (updateProductResponseRMS.getStatus().equals(
					CommonFlowConstants.STATUS_SUCCESS)) {
				Product product = message
						.getProperty(CommonFlowConstants.PRODUCT_INFO,
								PropertyScope.SESSION);
				// return product to payload
				Product productResponse = new Product();
				productResponse.setBaseSku(product.getBaseSku());
				List<Variant> variants = new ArrayList<>();
				for (Variant variant : product.getVariants()) {
					Variant newVariant = new Variant();
					newVariant.setSku(variant.getSku());
					variants.add(newVariant);
				}
				productResponse.setFreeShipping(null);
				productResponse.setVariants(variants);
				message.setPayload(productResponse);
			} else {
				message.setPayload(updateProductResponseRMS.getError());
			}

		} catch (Exception e) {
			throw new TransformerException(this, e);
		}

		return message;
	}

}
